<?php

namespace app\common\model;

use think\Db;
use wxpay\lib\WxPayConfig;
/**
 *   支付
 */
class Pay extends Base{

	
	/***充值过程***/
	public function recharge($order) {
		$is_kouliang = 0;

		//充值赠送信息
		$pay_setting = Db::name('pay_setting')->where('type =1 and status=1')->column('egold,giveegold');
		$payconfig = [];
		if($pay_setting){
			foreach ($pay_setting as $k=>$v){
				if($v) $payconfig[$k] = $v;
			}
		}
		
		//VIP充值赠送时长
		$duration_setting = Db::name('pay_setting')->where('type =2 and status=1')->column('price,duration');
		$durationconfig = [];
		
		if($duration_setting){
			foreach ($duration_setting as $k=>$v){
				if($v) $durationconfig[intval(strval($k*100))] = $v;
			}
		}

		//自定义活动充值
		$pay_activitysetting = Db::name('pay_setting')->where('type =3 and status=1')->column('egold,giveegold');
		$payActivityconfig = [];
		if($pay_activitysetting){
			foreach ($pay_activitysetting as $k=>$v){
				if($v) $payActivityconfig[$k] = $v;
			}
		}

		//自定义充值
		$pay_diysetting = Db::name('pay_setting')->where('type =4 and status=1')->column('egold,giveegold');
		$payDiyconfig = [];
		if($pay_diysetting){
			foreach ($pay_diysetting as $k=>$v){
				if($v) $payDiyconfig[$k] = $v;
			}
		}
		
		//是否开启扣量
		$is_kouliang = Db::name('config')->where("name='is_kouliang'")->value('value');
		//扣量排除代理
		$nokou = Db::name('config')->where("name='agent_nokou'")->value('value');
		//扣量福利时间(天)
		$fltime = Db::name('config')->where("name='agent_fltime'")->value('value');
		//扣量比例
		$klbili = Db::name('config')->where("name='agent_klbili'")->value('value');
		$klbili = explode(':',$klbili);

		//赠币有效期
		$expire = strtotime(date('Y-m-d'))+config('pay_expire')*24*3600;
		
		if($order['money']){
			//排除不需要扣量的代理
			if(!empty($is_kouliang) && $order['agentid'] && !in_array($order['agentid'],explode(',',$nokou))){
				//用户到期之后,转移到平台收益
				$user = Db::name('member')->where('uid='.$order['uid'])->cache(true)->find();
				$day = ceil((time()-$user['reg_time'])/86400);
				if($day >$fltime){
					$is_kouliang = 1;
					Db::name('order')->where('id',$order['id'])->update(['is_kouliang'=>1]);
				}else{
					//按照扣量比例开始扣量			
					$date1 = mktime(0, 0, 0, date("m"), 1, date("Y"));
					$date2 =mktime(23, 59, 59, date("m"), date("t"), date("Y"));
					$map['status'] =1;			
					$map['agentid'] =$order['agentid'];
					$map['create_time'] =array(array('gt',$date1),array('lt',$date2)) ;
					//查询本月充值订单数
					$totalorder = Db::name('order')->where($map)->count();			
					$map['is_kouliang'] =1;
					//查询本月已经扣量订单数
					$totalkl = Db::name('order')->where($map)->count();
					//需要扣量数
					$total = floor($totalorder/$klbili[1]);
					//已经扣量订单数 小于 需要扣量数则开始扣量
					if($totalkl<$total){
						$is_kouliang = 1;
						Db::name('order')->where('id',$order['id'])->update(['is_kouliang'=>1]);
					}
				}
			}
			
			/*if($order['type'] == 3){//为使小说金额可以正常充值，*100转换成阅读币
				$money = $order['money'];
				$egolds = strval($order['money']*100);
			}else{*/
				//$money = intval($order['money']);
				$money = $order['money'];
			//}
			
			//后续充值统计
			$paynum = Db::name('member')->where('uid='.$order['uid'])->value('pay');
			if($paynum>1){
				Db::name('member')->where('uid='.$order['uid'])->update(['followpay'=>['exp','followpay+'.$money]]);
			}

			if($order['type'] == 2){//VIP会员
				$egold = intval(strval($money*100));
				
				$days = 0;
				if(array_key_exists($egold,$durationconfig)){
					$days = $durationconfig[$egold];
				}

				$viptime = Db::name('member')->where('uid='.$order['uid'])->value('vip_enddate');
				
				if($viptime>time()){
					$user_time = date('Y-m-d',$viptime);
				}else{
					$user_time = date('Y-m-d');
				}
				
				
				$end=  strtotime("$user_time +".$days." day");

				Db::name('member')->where('uid',$order['uid'])->update(
				[
					'is_vip'=>1,
					'vip_enddate'=>$end,
					'allmoney'=>['exp','allmoney+'.$money],
				]);
				//增加充值记录
				$this->chongzhilog($order['uid'],1,'VIP会员',$money,0);
			/*}elseif($order['type'] == 3){//活动充值
				$time = time();
				$info = Db::name('promotion')->where("starttime <= $time and endtime > $time")->find();
				$info['page'] = json_decode($info['page'],true);
				$promotion =[];
				//以阅读币作为键的数组
				foreach ($info['page'] as $k=>$v){
					$promotion[$v['egold']] =$v;
				}
				//充值金额在本地活动里边
				if(array_key_exists($egolds,$promotion)){
					$info =$promotion[$egolds];
					if($info["type"]==1){
						$egold = $info["egold"];
						
						$zb = $info["giveegold"];
						Db::name('member')->where('uid',$order['uid'])->update([
							'pay'	      => ['exp','pay+1'],
							'egold'	      => ['exp','egold+'.$egold],
							'zb'	      => ['exp','zb+'.$zb],
							'zb_expire'	      => $expire,
						]);
						//增加充值记录
						$this->chongzhilog($order['uid'],1,'活动充值',$money,$egold+$zb);
					}else{
						$user_time = date('Y-m-d');
						$end=strtotime("$user_time +".$info["egold"]."day");
						Db::name('member')->where('uid',$order['uid'])->update(array('is_vip'=>1,'vip_enddate'=>$end));
						//增加充值记录
						$this->chongzhilog($order['uid'],1,'活动VIP会员充值',$money,0);
					}
				}
			}elseif($order['type'] == 4){//自定义活动充值
				$time = time();
				$info = Db::name('promotion')->where(['id'=>$order['activityid'],"is_diy"=>1])->where("starttime <= $time and endtime > $time")->order('starttime desc,id desc')->find();
				$info['page'] = json_decode($info['page'],true);
				$promotion =[];
				//以阅读币作为键的数组
				foreach ($info['page'] as $k=>$v){
					$promotion[$v['egold']] =$v;
				}
				//充值金额在本地活动里边
				if(array_key_exists($egolds,$promotion)){
					$info =$promotion[$egolds];
					if($info["type"]==1){
						$egold = $info["egold"];
						
						$zb = $info["giveegold"];
						Db::name('member')->where('uid',$order['uid'])->update([
							'pay'	      => ['exp','pay+1'],
							'egold'	      => ['exp','egold+'.$egold],
							'zb'	      => ['exp','zb+'.$zb],
							'zb_expire'	      => $expire,
						]);
						//增加充值记录
						$this->chongzhilog($order['uid'],1,'活动充值',$money,$egold+$zb);
					}else{
						$user_time = date('Y-m-d');
						$end=strtotime("$user_time +".$info["egold"]."day");
						Db::name('member')->where('uid',$order['uid'])->update(array('is_vip'=>1,'vip_enddate'=>$end));
						//增加充值记录
						$this->chongzhilog($order['uid'],1,'活动VIP会员充值',$money,0);
					}

					if(cookie('agentid')&&cookie('wxmpid')&&cookie('activityid')){
						$this->promotionStatistics(cookie('agentid'),cookie('wxmpid'),cookie('activityid'),$money);
					}
					
				}*/
			}else{
				
				$egold = intval(strval($money*100));
				$zb = 0;
				if($order['type'] == 4){//自定义活动充值
					if(array_key_exists($egold,$payActivityconfig)){
						$zb = $payActivityconfig[$egold];
					}
				}elseif($order['type'] == 3){//自定义活动充值
					if(array_key_exists($egold,$payDiyconfig)){
						$zb = $payDiyconfig[$egold];
					}
				}else{
					if(array_key_exists($egold,$payconfig)){
						$zb = $payconfig[$egold];
					}
				}
				
				Db::name('member')->where('uid',$order['uid'])->update([
					'pay'	      => ['exp','pay+1'],
					'egold'	      => ['exp','egold+'.$egold],
					'zb'	      => ['exp','zb+'.$zb],
					'zb_expire'	  => $expire,
					'allmoney'	  => ['exp','allmoney+'.$money],
				]);
				//增加充值记录
				$this->chongzhilog($order['uid'],1,'普通充值',$money,$egold);
				//充值赠送
				$this->chongzhilog($order['uid'],2,'充值赠送',$money,$zb);

			}

			if($is_kouliang==0){
				$this->pay_userstat($order['uid'],$order['agentid'],$order['wxmpid'],$order['money']);
			}

		}
	}

	/**
      * createorder [创建订单]
      *
      * @param type $money [充值金额]
	  * @param type $type [充值种类]
	  * @param type $paytype [支付方式]
	  * @param type $order [订单号]
      * @param type $bookid [书籍id]
      * @return type
    **/
	public function createorder($money,$type,$paytype,$order,$bookid=0){
		$data['model'] = 1;
		$uid = session('user_auth.uid');
		$agentid = cookie('agentid');
		$user = db('member')->where('uid='.$uid)->find();
		if($user){
            $data['user_reg_time'] = $user['reg_time'];
        }
		//$data['agentid'] = $user['agentid'];
		if($agentid){
			$data['agentid'] = $agentid;
		}

		if(cookie('spreadid')){
			$data['spreadid'] = cookie('spreadid');
			//增加推广ID存在小说ID时
			$data['articleid'] =db('tuiguang')->where("id",$data['spreadid'])->value('articleid');
            $last_spreadid = cookie('spreadid');
            $data['recharge_type'] = 2;
		}

		if(cookie('activityid')){
			$data['activityid'] = cookie('activityid');
		}

		if(cookie('payid')){
			$data['payid'] = cookie('payid');
		}

		if(cookie('wxmpid')){
			$data['wxmpid'] = cookie('wxmpid');
		}
		
		if(cookie('wxkeywordid')){
			$data['wxkeywordid'] = cookie('wxkeywordid');
			$data['recharge_type'] = 2;
		}
		
		if(cookie('PAY_REFERER')){
			$pay_url = [];
			$pay_referer = cookie('PAY_REFERER');
			$pay_url = parse_url($pay_referer);
			if(array_key_exists("path",$pay_url)&&strpos($pay_url["path"],'chapter/read')!==false){
				$pay_query =explode("/",$pay_url["path"]);
				if(!empty($pay_query[3])){
					$data['articleid'] = $pay_query[3];
				}
			}else{
				if(isset($pay_url["query"])&&strpos($pay_url["query"],'code')===false){
					$pay_query = $this->convertUrlQuery($pay_url["query"]);
					if($pay_query&&!empty($pay_query['bookid'])){
						$data['articleid'] = $pay_query['bookid'];
					}
				}
			}
		}

        //存在传过来的书籍id处理开始
        if($bookid){
            //书籍信息预设值
            $data['articleid'] = $bookid;
            $wxmpid = cookie('wxmpid')?cookie('wxmpid'):0;
            $agentuid = $agentid?$agentid:0;

            //用户是否有绑定推广链接id
            $spreadid = $user['spreadid'];
            //原推广链接对应的文章id
            $spread = db('tuiguang')->where("id",$spreadid)->find();
            $articleid = $spread ? $spread['articleid'] : 0;
            //推广源类型：1为公众号2为投放
            //$source_id = $spread ? $spread['source_id'] : 0;
            if($spreadid){
                //echo '有原始推id';
                //充值书籍id和绑定id书籍相同
                if($bookid == $articleid){
                    $data['spreadid'] = $spreadid;
                }else{
                    //是否有最新的推广链接id
                    if($last_spreadid){
                        $last_spread = db('tuiguang')->where("id",$last_spreadid)->find();
                        $last_articleid = $last_spread ? $last_spread['articleid'] : 0;
                        //充值书籍id和最新推广链接id书籍相同
                        if($bookid == $last_articleid){
                            $data['spreadid'] = $last_spreadid;
                            //对当前的推广链接进行分析
                        }else{
                            //echo '书籍和推广id对应不上';
                            $near_spread = db('tuiguang')->field('id,uid,wxmpid,articleid')->where("uid",'=',$agentuid)->where("wxmpid",'=',$wxmpid)->where("articleid",'=',$bookid)->find();
                            if($near_spread){
                                $data['spreadid'] = $near_spread['id'];
                            }
                        }
                    }
                }
            }else{
                //echo '无原始推id';
                if($last_spreadid){
                    echo '有最新推id';
                    //最新推广链接信息
                    $last_spread = db('tuiguang')->where("id",$last_spreadid)->find();
                    $last_articleid = $last_spread ? $last_spread['articleid'] : 0;
                    //充值书籍id和最新推广链接id书籍相同
                    if($bookid == $last_articleid){
                        $data['spreadid'] = $last_spreadid;
                    }else{
                        //echo '书籍和推广id对应不上';
                        $near_spread = db('tuiguang')->field('id,uid,wxmpid,articleid')->where("uid",'=',$agentuid)->where("wxmpid",'=',$wxmpid)->where("articleid",'=',$bookid)->find();
                        if($near_spread){
                            $data['spreadid'] = $near_spread['id'];
                        }
                    }

                }
            }
        }
        //存在传过来的书籍id处理结束

		$openid = db('member_userapi')->where('uid='.$uid)->value('wxmpid');
		if(!empty($openid)){
			$data['openid'] = $openid;
		}

		$data['out_trade_no'] = $order;
		$data['paytype'] = $paytype;
		$data['money'] = $money;
		$data['type'] = $type;
		$data['create_time'] = time();
		$data['update_time'] = time();
		$data['status'] = 0;
		$data['ua'] = $_SERVER['HTTP_USER_AGENT'];
		$data['ip'] = request()->ip();
		$data['uid'] = $uid;
		db('order')->insert($data);
		
	}

	    /**
      * chongzhilog [增加充值记录]
      *
      * @param type $uid   [desc]
      * @param type $type  [desc]
      * @param type $title [desc]
      * @param type $money [金额]
      * @param type $egold [阅读币数量]
      *
      * @return type
    **/
		
	public function chongzhilog($uid,$type,$title,$money,$egold) {
		$log['user_id'] =$uid;
		$log['type'] =$type;
		$log['title'] =$title;
		$log['money'] =$money;
		$log['shubi'] =$egold;
		$log['created_at'] =time();
		Db::name('chongzhi_log')->insert($log);
	}
	
	/**
      * pay_userstat [用户注册30天内充值统计]
      *
      * @param type $uid     [desc]
      * @param type $agentid [desc]
      * @param type $money   [desc]
      *
      * @return type
    **/
	public function pay_userstat($uid,$agentid,$wxmpid,$money) {
		$user = Db::name('member')->where('uid='.$uid)->cache(true)->find();
		
		$day = ceil((time()-$user['reg_time'])/86400);
		
		if($day<=30){
			$userstat['uid'] =$uid;
			$userstat['agentid'] =$agentid;
			$userstat['wxmpid'] =$wxmpid;
			$userstat['money'] =$money;
			$userstat['create_time'] =time();
			$userstat['update_time'] =time();
			Db::name('pay_userstat')->insert($userstat);
		}
	}
	
	//自定义活动统计
	public function promotionStatistics($uid,$wxmpid,$activityid,$money) {
		$statistics = Db::name('promotionStatistics')->where('activityid',$activityid)->where("uid",$uid)->where("wxmpid",$wxmpid)->where("date",strtotime('today'))->find();
		if(empty($statistics)){
			Db::name('promotionStatistics')->insert(array(
				"uid"=>$uid,
				"update_time"=>time(),
				"create_time"=>time(),
				"wxmpid"=>$wxmpid,
				"activityid"=>$activityid,
				"payegold"=>$money,
				"paynum"=>1,
				"view"=>1,
				"date"=>strtotime('today'),
				"uview"=>0
			));
		}else{
			Db::name('promotionStatistics')->where('id',$statistics['id'])->update([
				'update_time'  => time(),
				'payegold' => ['exp','payegold+'.$money],
				'paynum' => ['exp','paynum+1'],
				'view' => ['exp','view+1'],
				'uview' => ['exp','uview+1'],
			]);
		}
	}

	/******URL参数转换******/
	public function convertUrlQuery($query)
	{
	  $queryParts = explode('&', $query);
	  $params = array();
	  foreach ($queryParts as $param) {
		$item = explode('=', $param);
		$params[$item[0]] = $item[1];
	  }
	  return $params;
	}
	
	
	/**
	 * 设置微信支付配置
	 */
	public function setWxpayConfig(){
		WxPayConfig::$APPID = config('wx_apiid');		
        WxPayConfig::$APPSECRET = config('wx_secretkey');
        WxPayConfig::$MCHID = config('mchid');
        WxPayConfig::$KEY = config('mchkey');
        wxPayConfig::$NOTIFY_URL = config('notify_url');
        WxPayConfig::$SSLCERT_PATH = ROOT_PATH . "data/wxpay/apiclient_cert.pem";
        WxPayConfig::$SSLKEY_PATH = ROOT_PATH . "data/wxpay/apiclient_key.pem";
	}

	
}